import { useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
import { getMessage } from '@inbiz/react';
import { PauseOutlined } from '@ant-design/icons';
import PauseThumbIcon from '../../icon/PauseThumbIcon';
import ResumeListIcon from '../../icon/ResumeListIcon';
import ResumeThumbIcon from '../../icon/ResumeThumbIcon';
import { InBizUploadCtx } from '../../../context';

interface IProps {
  id: number;
  className: string;
}

const RauseResumeButton = (props: IProps) => {
  const { id, className } = props;
  const { uploader, statusEnum, thumbnail } = useContext(InBizUploadCtx);
  const [pausable, setPausble] = useState(true);
  const [resumable, setResumable] = useState(false);
  // 是否在暂停中
  const [pauseIng, $pauseIng] = useState(false)
  const pauseIngRef = useRef(false);
  const interRef = useRef<any>();
  const onClick = () => {
    if (pausable) {
      pauseIngRef.current = true;
      $pauseIng(true)
      uploader.methods.pauseUpload(id);
    } else if (resumable) {
      if (pauseIngRef.current) {
        return
      }
      let file = uploader.methods.getFile(id);
      file.status = statusEnum.PAUSED;
      uploader.methods.continueUpload(id, { isClearFile: false, isContinueUpload: true });
    }
  };
  const getButtonLabel = () => {
    return resumable ? 'resume' : 'pause';
  };
  const getButtonClassName = () => {
    return resumable ? 'react-fine-uploader-resume-button' : 'react-fine-uploader-pause-button';
  };
  const removeCustomEvent = () => {
    uploader.off('statusChange', onStatusChange);
    uploader.off('uploadChunkSuccess', onUploadChunkSuccess);
    uploader.off('complete', onUploadChunkSuccess);
    clearTimeout(interRef.current)
  };
  const onStatusChange = (fileId: number, oldStatus: string, newStatus: string) => {
    if (fileId === id) {
      if (newStatus == statusEnum.PAUSED) {
        $pauseIng(true)
        pauseIngRef.current = true;
        let file = uploader.methods.getFile(id);
        if (!file.isChunk) {
          clearTimeout(interRef.current)
          interRef.current = setTimeout(() => {
            $pauseIng(false)
            pauseIngRef.current = false;
          }, 1000)
        }
      }
      const cachePausable = newStatus === statusEnum.UPLOADING;
      const cacheResumable = newStatus === statusEnum.PAUSED;
      setPausble((state) => {
        if (state !== cachePausable) {
          return cachePausable;
        }
        return state;
      });
      setResumable((state) => {
        if (state !== cacheResumable) {
          return cacheResumable;
        }
        return state;
      });
      if (
        newStatus === statusEnum.DELETED ||
        newStatus === statusEnum.CANCELED ||
        newStatus === statusEnum.UPLOAD_SUCCESSFUL
      ) {
        removeCustomEvent();
      }
    }
  };
  const onUploadChunkSuccess = (fileId: number) => {
    if (fileId === id && pauseIngRef.current) {
      pauseIngRef.current = false;
      $pauseIng(false)
    }
  }
  useEffect(() => {
    uploader.on('statusChange', onStatusChange);
    uploader.on('uploadChunkSuccess', onUploadChunkSuccess);
    uploader.on('complete', onUploadChunkSuccess);
    return () => {
      removeCustomEvent();
    };
  }, [uploader]);
  const renderButtonContent = useMemo(() => {
    if (resumable) {
      return !thumbnail ? <ResumeListIcon /> : <ResumeThumbIcon />;
    }
    return !thumbnail ? (
      <PauseOutlined style={{ fontSize: '16px', color: 'var(--inbiz-color-primary)' }} />
    ) : (
      <PauseThumbIcon />
    );
  }, [resumable, pausable]);
  return pausable || resumable ? (
    <button
      aria-label={getButtonLabel()}
      className={`react-fine-uploader-pause-resume-button ${getButtonClassName()} ${className || ''
        }`}
      disabled={!pausable && !resumable || pauseIng}
      onClick={onClick}
      type="button"
      title={pauseIng ? getMessage('inbizUpload.paused') : ''}
    >
      {renderButtonContent}
    </button>
  ) : null;
};

export default RauseResumeButton;
